package jk.fox.spring.container;

import jk.fox.common.payload.container.RpcContainer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.Assert;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author cuichao
 * @Description: SpringRpcContainer
 * @Date: create in 2020/5/28 13:49
 */
public class SpringRpcContainer implements RpcContainer,BeanFactoryAware {


    ConfigurableListableBeanFactory beanFactory;
    private final ConcurrentMap<String,Object> referenceObjects = new ConcurrentHashMap<>(32);

    @Override
    public Object getService(String key) {
        return beanFactory.getBean(key);
    }

    @Override
    public void addService(String key, Object provider) {

        beanFactory.registerSingleton(key,provider);
    }

    @Override
    public Object getReference(String key) {
        return referenceObjects.getOrDefault(key,null);
    }

    @Override
    public void addReference(String key, Object consumer) {
        referenceObjects.put(key,consumer);
    }
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        Assert.isInstanceOf(ConfigurableListableBeanFactory.class, beanFactory, "AnnotationInjectedBeanPostProcessor requires a ConfigurableListableBeanFactory");
        this.beanFactory =  (ConfigurableListableBeanFactory)beanFactory;
    }





}
